import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Scanner;

public class TCPEchoSever {
    ServerSocket socket;
    //定义客户端
    public  TCPEchoSever(int pase) throws IOException {
        if(pase<1024||pase>65535){
            System.out.println("端口号不符合条件");
        }
       this.socket=new ServerSocket(pase);
    }
    public void start() throws IOException {
        System.out.println("服务器已启动");
        System.out.println("端口号"+socket.getLocalPort()+"地址"+socket.getInetAddress());
        //循环接收连接需求
        while (true){
            Socket clientsocket=socket.accept();
            //创建一个方法去接收客服端的内容
            reviceports(clientsocket);

        }
    }
    public void reviceports(Socket clientsocket) throws IOException {
        System.out.println("端口号"+socket.getLocalPort()+"地址"+socket.getInetAddress());
        //使用输出流和输入流进行接收
        while (true){
            try(InputStream inputStream= clientsocket.getInputStream();
                OutputStream outputStream= clientsocket.getOutputStream()){
                Scanner scanner=new Scanner(inputStream);//嵌入输入流
                while (!scanner.hasNextLine()){
                    System.out.println("客服端下线了"+socket.getLocalPort()+socket.getInetAddress());
                }
                //获取用户发来的内容
                String request=scanner.nextLine();
                //对内容进行计算响应
                String respose=Calculation(request);
                //把响应写入输出流
                PrintWriter printWriter=new PrintWriter(outputStream);
                printWriter.println(respose);
                //刷新缓冲区
                printWriter.flush();
                //打印
                System.out.printf("[%s:%d] request=%s,respose=%s\n",clientsocket.getInetAddress().toString(),clientsocket.getPort(),request,respose);
            }
        }
    }
    public String Calculation(String respose){
        return respose;
    }

    public static void main(String[] args) throws IOException {
        TCPEchoSever tcpEchoSever=new TCPEchoSever(8888);
        tcpEchoSever.start();
    }
}
